package com.leetcode.p300;

import com.utils.DataUtils;

import java.util.Arrays;
import java.util.HashMap;

public class Test350 {

    public int[] intersect(int[] nums1, int[] nums2) {
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int k : nums1) {
            if (!map.containsKey(k)) {
                map.put(k, 1);
            } else {
                map.put(k, map.get(k) + 1);
            }
        }

        int[] result = new int[nums2.length];

        int index = 0;
        for (int k : nums2) {
            if (map.containsKey(k)) {
                int dataCount = map.get(k);
                result[index] = k;
                index++;
                if (dataCount > 1) {
                    map.put(k, dataCount - 1);
                } else {
                    map.remove(k);
                }
            }
        }

        return Arrays.copyOf(result, index);
    }

    public static void main(String[] args) {
        Test350 test = new Test350();

        int[] nums1 = new int[]{1, 2, 2, 1, 3, 3};
        int[] nums2 = new int[]{2, 2, 3, 3};

        int[] result = test.intersect(nums1, nums2);

        DataUtils.printArray(result);
    }
}
